package com.liusand.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.liusand.common.ThreadLocalUtils;
import com.liusand.exception.EmployeeException;
import com.liusand.mapper.EmployeeMapper;
import com.liusand.pojo.PageInfo;
import com.liusand.service.EmployeeService;
import com.liusand.pojo.Employee;
import com.liusand.vo.EmployeeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author :liusha
 * packageName :com.liusand.reggiecode.db.service.impl
 * fileName :AdminServiceImpl
 * creationTime :2022/11/20 18:22
 */
@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public EmployeeVo findByUsernameAndPassword(Employee employee) {
        Employee e = employeeMapper.findByUsernameAndPassword(employee.getUsername(),SecureUtil.md5(employee.getPassword()));
        if(e == null){
            return null;
        }
        if(e.getStatus() == 0){
            return null;
        }
        EmployeeVo vo = new EmployeeVo();
        BeanUtils.copyProperties(e, vo);

//        DateTime now = new DateTime();
//        DateTime newTime = now.offsetNew(DateField.MINUTE, 10);

        Map<String,Object> payload = new HashMap<String,Object>();
        payload.put("username", e.getUsername());
        payload.put("id", e.getId());
        String key = "QWER";
        String token = JWTUtil.createToken(payload, key.getBytes());

        vo.setToken(token);
        redisTemplate.opsForValue().set("employee_token:"+token, JSON.toJSONString(e),30 , TimeUnit.MINUTES);
        return vo;
    }

    @Override
    public PageInfo<Employee> page(String name, Integer page, Integer pageSize) {
        int start = (page - 1) * pageSize;
        List<Employee> employees = employeeMapper.page(name, start, pageSize);
        PageInfo<Employee> pageInfo = new PageInfo<Employee>();
        pageInfo.setRecords(employees);
        pageInfo.setSize(pageSize);
        pageInfo.setCurrent(page);
        Long total = employeeMapper.countPage(name);
        pageInfo.setTotal(total);
        return pageInfo;
    }

    @Override
    public Employee findEmployeeById(String id) {
        Employee employee = employeeMapper.findEmployeeById(id);
        return employee;
    }

    @Override
    public boolean saveEmployee(Employee employee) {
        Employee e = employeeMapper.findEmployeeByUsername(employee.getUsername());
        if(e != null){
            throw new EmployeeException("'"+e.getUsername()+"'已存在");
        }
        employee.setId(IdUtil.getSnowflakeNextIdStr());
        if(employee.getStatus() == null){
            employee.setStatus(1);
        }
        if(!StringUtils.hasText(employee.getPassword())){
            employee.setPassword(SecureUtil.md5("123456"));
        }
        String id = ThreadLocalUtils.getId();

        if(!StringUtils.hasText(employee.getCreateUser())){
            employee.setCreateUser(id);
        }
        if(!StringUtils.hasText(employee.getUpdateUser())){
            employee.setUpdateUser(id);
        }
        return employeeMapper.saveEmployee(employee) > 0;
    }

    @Override
    public boolean updateEmployee(Employee employee) {
        Employee e = employeeMapper.findEmployeeByUsername(employee.getUsername());
        if(e != null && !e.getId().equals(employee.getId())){
            throw new EmployeeException("'"+e.getUsername()+"'已存在");
        }
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(ThreadLocalUtils.getId());
        return employeeMapper.updateEmployee(employee) > 0;
    }
}
